<template>
  <div>
   <el-table
      :data="tableData.filter(data => !search || data.title.toLowerCase().includes(search.toLowerCase()))"
      style="width: 100%">
      <el-table-column
        label="书籍Id"
        prop="id">
      </el-table-column>
  
      <el-table-column
        label="书名"
        prop="title">
      </el-table-column>
      
      <el-table-column
        label="读者名称"
        prop="readerName">
      </el-table-column>
  
      <el-table-column
        label="借阅日期"
        prop="borrowDate">
      </el-table-column>
  
      <el-table-column
        label="截止还书日期"
        prop="deadline">
      </el-table-column>
  
    
      <el-table-column
        align="right">
        <template slot="header" slot-scope="scope">
          <el-input
            v-model="search"
            size="mini"
            placeholder="输入关键字搜索"/>
            
        </template>
  
        <template slot-scope="scope">
          <!-- 这里添加了确认框，所以点击用@confirm代替@click -->
          <el-popconfirm title="确定归还图书吗？"  @confirm="handleDelete(scope.$index, scope.row)"> 
            <el-button
              size="mini"
              type="danger"
              slot="reference">归还图书</el-button>
               <!-- @click="handleDelete(scope.$index, scope.row)" -->
               <!-- 如实不添加确认框，在这里用click -->
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    </br>
    </br>
    <el-button
        @click="showBorrowDialog"
        size="mini"
        type="success"
        slot="reference">借书</el-button>  
  
  
      <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      @close="resetForm">
      <el-form :model="form" ref="bookForm">
        <!-- 输入项可以根据需要添加，这里以书籍标题为例 -->
        <el-form-item label="书籍Id" :label-width="formLabelWidth">
          <el-input v-model="form.id" type="number" step="1"></el-input>
        </el-form-item>
        <el-form-item label="书名" :label-width="formLabelWidth">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="读者账号" :label-width="formLabelWidth">
          <el-input v-model="form.readerId"></el-input>
        </el-form-item>
        <el-form-item label="读者名称" :label-width="formLabelWidth">
          <el-input v-model="form.readerName"></el-input>
        </el-form-item>
        <!-- 添加其他必要的输入项，例如读者ID、姓名等 -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmBorrow">确 定</el-button>
      </span>
    </el-dialog>
   
  </div>
  
    
  </template>
  
  <script>
  import { mapState } from 'vuex';
  export default {
    name: 'HelloWorld',
    props: {
    },
    computed: {
    ...mapState(['books',"tableData"]),
    libraryBooks() {
      // 这里直接返回store中的books作为libraryBooks
      return this.books;
    },
  },
    data() {
        return {
           dialogVisible: false, // 控制对话框是否显示
           dialogTitle: '新增借书记录',
          formLabelWidth: '120px', // 表单标签宽度
            form: { 
            id: '',  
            title: '',  
            readerId: '',  
            readerName: '' ,
            }, 
          
            book: { // 使用 data 来存储书籍信息  
            id: '',  
            title: '',  
            readerName: '' ,
            borrowDate:'',
            deadline:'',
            }, 
          dialogEditVisible: false, // 控制编辑对话框是否显示
          editBook: {}, // 存储正在编辑的图书信息
          search: '',
          
        }
      },
      methods: {

      
async handleDelete(index, row) {
  console.log(index, row);
  const bookIdToReturn = row.id; // 确保row对象包含id
  console.log(bookIdToReturn);
  try {
    await this.$store.dispatch('returnBook', bookIdToReturn);
    this.tableData.splice(index, 1); // 成功后从界面移除
    this.$message.success(`图书已成功归还。`);
  } catch (error) {
    console.error("归还图书时发生错误:", error);
    this.$message.error("归还图书失败，请重试。");
  }
},
       // 显示借书对话框
      showBorrowDialog() {
        this.dialogVisible = true;
      },
      // 重置表单
      resetForm() {
        this.$refs.bookForm.resetFields();
      },
      // 添加新借书记录的方法，需要根据您的数据管理方式进行调整
      addBookRecord(book) {
        // 示例：将新记录添加到数组或调用API保存到数据库
        this.tableData.push(book);
        console.log('新增借书记录:', book);
      },

    async confirmBorrow() {
    // 查找书库中是否有这本书
    const bookInLibrary = this.libraryBooks.find(book => book.title === this.form.title);
  this.form.id = Number.parseInt(this.form.id, 10);
  if (isNaN(this.form.id)) {
    // 处理非数字输入的情况，比如提示错误或赋予默认值
    this.$message.error("请输入有效的书籍ID！");
    return;
  }
  if (bookInLibrary) {
    // 书库中有这本书，继续借书逻辑
    if (bookInLibrary.copies > 0) {
      // 减少副本数量应通过调用Vuex action完成
      await this.$store.dispatch('borrowBook', bookInLibrary.id);
      // 计算并设置借阅和截止日期
      const currentDate = new Date();
      const borrowDate = currentDate.toLocaleDateString();
      const deadlineObj = new Date(currentDate);
      deadlineObj.setDate(deadlineObj.getDate() + 60); // 假设增加60天为截止日期
      const deadline = deadlineObj.toLocaleDateString();

      // 创建新的借书记录对象
      const newBorrowedBook = {
        id: this.form.id,
        title: this.form.title,
        readerName: this.form.readerName,
        borrowDate: borrowDate,
        deadline: deadline
      };

      
      // 添加借书记录
      this.addBookRecord(newBorrowedBook);
      this.form.id = '';
      this.form.title = '';
      this.form.readerId = '';
      this.form.readerName = '';

      this.$message.success(`已成功借阅《${bookInLibrary.title}》，剩余副本：${bookInLibrary.copies}`);
      this.dialogVisible = false; // 关闭对话框
    } else {
      this.$message.error(`《${this.form.title}》已无剩余副本可借阅。`);
    }
  } else {
    // 书库中不存在这本书，给用户提示
    this.$message.error(`图书馆中不存在《${this.form.title}》这本书。`);
    return; // 停止执行后续逻辑
  }

  },
      }
      
  }
  </script>
  
  <!-- Add "scoped" attribute to limit CSS to this component only -->
  <style scoped>
  .in {
    width:200px;
  }
  
  </style>